package com.cupk.security;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException; // 确保导入这个
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets; // [关键] 确保这个 import 存在
import java.security.Key;
import java.util.Date;

@Component
public class JwtTokenProvider {
    private static final Logger logger = LoggerFactory.getLogger(JwtTokenProvider.class);

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Value("${jwt.expirationMs}")
    private int jwtExpirationMs;

    public String generateToken(Authentication authentication) {
        UserDetails userPrincipal = (UserDetails) authentication.getPrincipal();
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + jwtExpirationMs);
        return Jwts.builder()
                .setSubject(userPrincipal.getUsername())
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(key(), SignatureAlgorithm.HS256)
                .compact();
    }

    // --- 这是最关键的修改 ---
    private Key key() {
        // 直接将配置文件中的密钥字符串转换为 UTF-8 编码的字节数组
        return Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8));
    }

    public String getUsernameFromJWT(String token) {
        Claims claims = Jwts.parserBuilder().setSigningKey(key()).build()
                .parseClaimsJws(token).getBody();
        return claims.getSubject();
    }

    public boolean validateToken(String authToken) {
        try {
            Jwts.parserBuilder().setSigningKey(key()).build().parse(authToken);
            return true;
        } catch (MalformedJwtException ex) {
            logger.error("无效的 JWT 令牌: {}", ex.getMessage());
        } catch (ExpiredJwtException ex) {
            logger.error("过期的 JWT 令牌: {}", ex.getMessage());
        } catch (UnsupportedJwtException ex) {
            logger.error("不支持的 JWT 令牌: {}", ex.getMessage());
        } catch (IllegalArgumentException ex) {
            logger.error("JWT claims 字符串为空: {}", ex.getMessage());
        } catch (SignatureException ex) {
            logger.error("JWT 签名验证失败: {}", ex.getMessage());
        }
        return false;
    }
}